package com.sservice.service.service.impl;

import com.sservice.model.dao.PurchaseLogMapper;
import com.sservice.model.dao.PurchaseMapper;
import com.sservice.model.entity.Purchase;
import com.sservice.model.vo.PurchaseVo;
import com.sservice.service.service.PurchaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class PurchaseServiceImpl implements PurchaseService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PurchaseMapper dataDao;
    @Autowired
    private PurchaseLogMapper logDao;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dataDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Purchase record) {
        return dataDao.insert(record);
    }

    @Override
    public int insertSelective(Purchase record) {
        return dataDao.insertSelective(record);
    }

    @Override
    public Purchase selectByPrimaryKey(Integer id) {
        return dataDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Purchase record) {

        int update_ = dataDao.updateByPrimaryKeySelective(record);

        return update_;
    }

    @Override
    public int updateByPrimaryKey(Purchase record) {
        return dataDao.updateByPrimaryKey(record);
    }

    @Override
    public Map<String, Object> report() {


        return null;
    }

    @Override
    public int queryCount(PurchaseVo record) {
        return dataDao.queryByCount(record);
    }

    @Override
    public List<PurchaseVo> queryByPage(PurchaseVo record) {
        return dataDao.queryByPage(record);
    }

    /**
     * 采购单数量变更，如果交易中数量增加2，则record参数中对应字段值为2，如果减少2，则对应字段值为-2
     *
     * @param id
     * @param number
     * @param charged
     * @param charging
     * @return
     */
    @Override
    @Transactional
    public int changeNumber(Integer id, BigDecimal number, BigDecimal charged, BigDecimal charging) {
        Purchase purchase = dataDao.selectByPrimaryKey(id);
        Purchase purchase1 = new Purchase();
        purchase1.setId(purchase.getId());
        purchase1.setNumber(purchase.getNumber().add(number));
        purchase1.setNumberCharged(purchase.getNumberCharged().add(charged));
        purchase1.setNumberCharging(purchase.getNumberCharging().add(charging));
        if (purchase1.getNumber().compareTo(BigDecimal.ZERO) == -1 || purchase1.getNumberCharged().compareTo(BigDecimal.ZERO) == -1 || purchase1.getNumberCharged().compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("采购数据错误");
        }
        return dataDao.updateByPrimaryKeySelective(purchase1);
    }
}